package me.nereo.multi_image_selector.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.R;
import me.nereo.multi_image_selector.bean.Image;

/**
 * 图片Adapter
 * Created by Nereo on 2015/4/7.
 */
public class ImageGridAdapter extends BaseAdapter {

    private static final int TYPE_CAMERA = 0;
    private static final int TYPE_NORMAL = 1;

    private Context mContext;

    private LayoutInflater mInflater;
    private boolean showCamera = true;
    private boolean showSelectIndicator = true;

    private List<Image> mImages = new ArrayList<Image>();
    private List<Image> mSelectedImages = new ArrayList<Image>();

    private int mItemSize;
    private GridView.LayoutParams mItemLayoutParams;
//    ImageLoaderConfiguration configuration;
//    DisplayImageOptions displayImageOptions;
    public OnItemClickListener mOnItemClickListener;
    public interface OnItemClickListener{
    	public void onItemClick(int pos,Image image);
    }
    public ImageGridAdapter(Context context, boolean showCamera,OnItemClickListener onItemClickListener){
        mContext = context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.showCamera = showCamera;
        this.mOnItemClickListener = onItemClickListener;
        mItemLayoutParams = new GridView.LayoutParams(GridView.LayoutParams.MATCH_PARENT, GridView.LayoutParams.MATCH_PARENT);
//        configuration = ImageLoaderConfiguration  
//                .createDefault(context);
//        ImageLoader.getInstance().init(configuration);
//        displayImageOptions = new DisplayImageOptions.Builder()
//        .showImageOnLoading(R.drawable.default_error) // resource or drawable
//        .showImageForEmptyUri(R.drawable.default_error) // resource or drawable
//        .showImageOnFail(R.drawable.default_error) // resource or drawable
//        .resetViewBeforeLoading(false).build();  // default
    }
    /**
     * 显示选择指示器
     * @param b
     */
    public void showSelectIndicator(boolean b) {
        showSelectIndicator = b;
    }

    public void setShowCamera(boolean b){
        if(showCamera == b) return;

        showCamera = b;
        notifyDataSetChanged();
    }

    public boolean isShowCamera(){
        return showCamera;
    }

    /**
     * 选择某个图片，改变选择状态
     * @param image
     */
    public void select(Image image) {
        if(mSelectedImages.contains(image)){
            mSelectedImages.remove(image);
        }else{
            mSelectedImages.add(image);
        }
//        notifyDataSetChanged();
    }

    /**
     * 通过图片路径设置默认选择
     * @param resultList
     */
    public void setDefaultSelected(ArrayList<String> resultList) {
        for(String path : resultList){
            Image image = getImageByPath(path);
            if(image != null){
                mSelectedImages.add(image);
            }
        }
        if(mSelectedImages.size() > 0){
            notifyDataSetChanged();
        }
    }

    private Image getImageByPath(String path){
        if(mImages != null && mImages.size()>0){
            for(Image image : mImages){
                if(image.path.equalsIgnoreCase(path)){
                    return image;
                }
            }
        }
        return null;
    }

    /**
     * 设置数据集
     * @param images
     */
    public void setData(List<Image> images) {
        mSelectedImages.clear();

        if(images != null && images.size()>0){
        	mImages.clear();
        	mImages.addAll(images);
        }else{
            mImages.clear();
        }
        notifyDataSetChanged();
    }

    /**
     * 重置每个Column的Size
     * @param columnWidth
     */
    public void setItemSize(int columnWidth) {

        if(mItemSize == columnWidth){
            return;
        }

        mItemSize = columnWidth;

        mItemLayoutParams = new GridView.LayoutParams(mItemSize, mItemSize);

        notifyDataSetChanged();
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        if(showCamera){
            return position==0 ? TYPE_CAMERA : TYPE_NORMAL;
        }
        return TYPE_NORMAL;
    }

    @Override
    public int getCount() {
        return showCamera ? mImages.size()+1 : mImages.size();
    }

    @Override
    public Image getItem(int i) {
        if(showCamera){
            if(i == 0){
                return null;
            }
            return mImages.get(i-1);
        }else{
            return mImages.get(i);
        }
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
    	 final ViewHolde holde;
        int type = getItemViewType(i);
        if(view == null){
        	view = mInflater.inflate(R.layout.list_item_image, viewGroup, false);
            holde = new ViewHolde();
            holde.image = (ImageView) view.findViewById(R.id.image);
            holde.indicator = (ImageView) view.findViewById(R.id.checkmark);
            holde.mask = view.findViewById(R.id.mask);
            holde.flytCamera = (FrameLayout) view.findViewById(R.id.flyt_camera);
            holde.flytSelect = (FrameLayout) view.findViewById(R.id.flyt_select);
            view.setTag(holde);
        }else{
            holde = (ViewHolde) view.getTag();
        }
        if(type == TYPE_CAMERA){
            holde.flytCamera.setVisibility(View.VISIBLE);
            holde.flytSelect.setVisibility(View.GONE);
        }else if(type == TYPE_NORMAL){
          	  holde.flytCamera.setVisibility(View.GONE);
              holde.flytSelect.setVisibility(View.VISIBLE);
              holde.bindData(getItem(i));
        }
        holde.flytCamera.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mOnItemClickListener!=null){
					mOnItemClickListener.onItemClick(i,getItem(i));
				}
			}
		});
        holde.flytSelect.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_UP){
					if(mOnItemClickListener!=null){
						mOnItemClickListener.onItemClick(i,getItem(i));
					}
					 if(showSelectIndicator){
						 holde.indicator.setVisibility(View.VISIBLE);
			                if(mSelectedImages.contains(getItem(i))){
			                    // 设置选中状态
			                	holde.indicator.setImageResource(R.drawable.btn_selected);
			                	holde.mask.setVisibility(View.VISIBLE);
			                }else{
			                    // 未选择
			                	holde.indicator.setImageResource(R.drawable.btn_unselected);
			                	holde.mask.setVisibility(View.GONE);
			                }
			            }else{
			            	holde.indicator.setVisibility(View.GONE);
			            }
				}
				return true;
			}
		});
        /** Fixed View Size */
        GridView.LayoutParams lp = (GridView.LayoutParams) view.getLayoutParams();
        if(lp.height != mItemSize){
            view.setLayoutParams(mItemLayoutParams);
        }

        return view;
    }

    class ViewHolde {
        ImageView image;
        ImageView indicator;
        View mask;
        FrameLayout flytCamera;
        FrameLayout flytSelect;

        void bindData(final Image data){
            if(data == null) return;
            // 处理单选和多选状态
            if(showSelectIndicator){
                indicator.setVisibility(View.VISIBLE);
                if(mSelectedImages.contains(data)){
                    // 设置选中状态
                    indicator.setImageResource(R.drawable.btn_selected);
                    mask.setVisibility(View.VISIBLE);
                }else{
                    // 未选择
                    indicator.setImageResource(R.drawable.btn_unselected);
                    mask.setVisibility(View.GONE);
                }
            }else{
                indicator.setVisibility(View.GONE);
            }
            File imageFile = new File(data.path);
            if(mItemSize > 0) {
            	Glide.with(mContext).load(imageFile).placeholder(R.drawable.default_error).centerCrop().into(image);
            }
        }
    }
}
